<template>
    <div class="container-xl my-home-div">

        <div class="my-home-div-line row">
            <div class="col">
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-a-icon_FolderOpen"></use>
                </svg>
                资料
            </div>
            <div class="rongliang" :style="{ width: '240px' }">
                容量：{{ useflow.usesize }} / {{ useflow.size }}
            </div>
            <div class="col col-progress" :style="{ width: '130px' }">
                <el-progress :percentage="useflow.percentagesize" />
            </div>
            <div class="rongliang" :style="{ width: '240px' }">
                月流量：{{ useflow.useflow }} / {{ useflow.flow }}
            </div>
            <div class="col col-progress" :style="{ width: '130px' }">
                <el-progress :percentage="useflow.percentageflow" />
            </div>
            <div class="text-right" :style="{ width: '180px' }">
                <el-upload class="upload-demo" :disabled="!!percentage"
                    action="https://jsonplaceholder.typicode.com/posts/" :auto-upload="true" :http-request="request"
                    :show-file-list="false">
                    <el-button :disabled="!!percentage" ref="buttonRef" size="default" type="primary">
                        <el-icon :size="20">
                            <Upload />
                        </el-icon>
                        &nbsp;
                        {{ percentage ? '上传中...' + percentage + '%' : '上传文件' }}
                    </el-button>
                </el-upload>
            </div>
        </div>
        <div class="row min-height" v-if="count" v-loading="loading">
            <div class="col">
                <table class="table">
                    <tbody>
                        <tr class="thead">
                            <td scope="col" class="colbt">
                                文件名
                            </td>
                            <td width="180" scope="col" class="text-center">文件类型</td>
                            <td width="180" class="text-center" scope="col">上传时间</td>
                            <td width="180" scope="col" class="text-center">文件大小</td>
                            <td width="174" class="text-center" scope="col">操作</td>
                        </tr>

                        <tr class="thead2" v-for="(v, key) in tableDate" :key="key">
                            <td class="colbt">{{ v.name }} </td>
                            <td class="text-center">{{ v.type }}</td>
                            <td class="text-center">{{ TimeYH2(v.createdAt) }}</td>
                            <td class="text-center">{{ renderSize(Number(v.size)) }}</td>
                            <td class="text-center">
                                <el-tooltip effect="dark" content="下载链接有效期：5分钟" placement="left">
                                    <el-button :icon="Download" size="default" @click="download(v)">
                                        下载
                                    </el-button>
                                </el-tooltip>
                                <el-button size="default" v-show="isAdmin" @click="del(v)">删除</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="row" v-if="count">
            <div class="col text-right">
                <el-pagination :page-size="limit" :total="count" @current-change="change" layout="prev, pager, next"
                    :current-page="Math.floor(offset / limit) + 1"></el-pagination>
            </div>
        </div>
        <el-empty v-if="!count" image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />
    </div>
</template>

<script setup lang="ts">
import { Download, Upload } from '@element-plus/icons-vue';
import OSS from 'ali-oss';
import { ElButton, ElMessage, ElMessageBox, ElNotification, ElUpload, UploadRequestOptions, } from 'element-plus';
import { debounce } from 'underscore';
import { v4 } from 'uuid';
import { computed, h, onMounted, ref, watch } from 'vue';
import { asynccreateteamfile, asyncdelectteamfile, asyncgetteamfile, asyncupdateteamflow, asyncuploadAccess, ossupload } from '../../../api';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { TimeYH2 } from '../../../util/time';
import { updateoss2 } from '../../../util/updateoss';

const p = defineProps<{
    data: Studycodemodel.Iteam, isAdmin?: 0 | 1 | 2
    user?: Studycodemodel.Iuser,
    flow?: Studycodemodel.Iteamflow,
    setflow?: Function
}>()


const tableDate = ref<Studycodemodel.Iteamfile[]>([])
const percentage = ref(0)

/**
 * 大小
 */
// const size = computed(() => Number(p.size))

/**
 * 流量
 */
// const flow = computed(() => Number(p.flow))

/**
 * 名称
 */
// const name = computed(() => p.name)

const open1 = () => {
    ElNotification({
        title: '上传中',
        message: h('i', { style: 'color: teal' }, 'This is a reminder'),
    })
}


async function del(V: Studycodemodel.Iteamfile) {
    if (!p.isAdmin) {
        ElMessage.error('没有权限')
    }
    ElMessageBox.confirm("确定要删除?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "",
        type: "warning",
    })
        .then(async () => {
            try {
                await asyncdelectteamfile(V)
                if (V.url) {
                    await o.value?.delete(V.url)
                }
                start()
            } catch (e) {
                ElMessage({
                    message: String(e),
                    type: "error",
                });
            }
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "已取消",
            });
        });

}


const useflow = computed(() => {
    const { usesize = 0, size = 1021 * 1024 * 1024 * 5, flow = 1021 * 1024 * 1024 * 10, useflow = 0 } = p.flow || {}
    return {
        size: renderSize(size),
        usesize: renderSize(usesize),
        flow: renderSize(flow),
        useflow: renderSize(useflow),
        percentageflow: Math.floor(useflow / flow * 100),
        percentagesize: Math.floor(usesize / size * 100),
        _usesize: usesize,
        _size: size,
        _flow: flow,
        _useflow: useflow,
    }
})



async function download(name: Studycodemodel.Iteamfile) {
    if (useflow.value._useflow > useflow.value._flow) {
        ElMessage.error('本月团队资料流量已用完，如需帮助请联系助教老师或管理员')
        return
    }
    const data = o.value?.signatureUrl(String(name.url), {
        expires: 300
    })
    await asyncupdateteamflow({ ID: p.flow?.ID, useflow: p.flow?.useflow, size: name.size, teamid: p.data.ID, name: name.name, teamfileid: name.ID })
    window.open(data, '_blank')
    if (p.setflow) {
        p.setflow()
    }

}

const upload = ref<typeof ElUpload>();
async function request(option: UploadRequestOptions) {
    if (upload.value) upload.value.clearFiles();
    if (option.file.size > 1024 * 1024 * 1024) {
        ElMessage.warning('提示：文件资料大小为1G以内，如需上传更大文件请联系助教老师')
        return
    }

    if (useflow.value._usesize > useflow.value._size) {
        ElMessage.error('团队存储空间已满，如需帮助请联系助教老师或管理员')
        return
    }
    if (option.file.name.length > 128) {
        ElMessage.error('文件名称最大长度128')
        return
    }
    try {
        const res = await asyncuploadAccess({ teamid: p.data.ID })
        const v = v4()
        const d = await updateoss2([option.file], { bucket: 'ojteam', url: `${p.data.ID}/${v}/${option.file.name}`, res }, () => { }, {
            progress
        });
        percentage.value = 0
        const sp = option.file.name.split('.')
        await asynccreateteamfile({
            name: option.file.name,
            url: d.name,
            size: option.file.size,
            type: sp.length === 1 ? '' : sp.pop(),
            teamid: p.data.ID
        })
        start()
        if (p.setflow) {
            p.setflow()
        }
    } catch (e: any) {
        console.log(e)
        ElMessage.error(e)
    }
}

function progress(per: number, checkpoint: any, res: any) {
    percentage.value = Math.floor(per * 100)
}


function renderSize(value: number) {
    if (!value) {
        return "0 Bytes";
    }
    var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
    var index = 0;
    var srcsize = parseFloat(String(value));
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    var size = srcsize / Math.pow(1024, index);
    return size.toFixed(2) + unitArr[index];
}

const bucketobj = ref()

const count = ref(0)
const offset = ref(0);
const limit = ref(10);
const loading = ref(false)
const name = ref('')
function debounce1() {
    return debounce(() => {
        let _like: [keyof Studycodemodel.Iteamfile, any] | undefined;
        if (name.value) {
            _like = ["name", name.value];
        }
        loading.value = true
        asyncgetteamfile({
            _offset: offset.value,
            _limit: limit.value,
            _like,
            teamid: p.data.ID,
        }).then(e => {
            loading.value = false
            tableDate.value = e.rows
            count.value = e.count
        })
        if (p.setflow) {
            p.setflow()
        }
    }, 300);
}
const start = debounce1();

watch([offset, limit, name], (e, r) => {
    start();
});

const o = ref<OSS>()

onMounted(async () => {
    const res = await ossupload()
    o.value = new OSS({
        region: "oss-cn-qingdao",
        accessKeyId: res.accessKeyId,
        accessKeySecret: res.accessKeySecret,
        stsToken: res.securityToken,
        bucket: 'ojteam',
        refreshSTSToken: async () => {
            const info = await ossupload();
            return {
                accessKeyId: info.accessKeyId,
                accessKeySecret: info.accessKeySecret,
                stsToken: info.securityToken
            }
        }

    })
    start()
})

function change(r: number) {
    offset.value = (r - 1) * 10;
}


</script>

<style scoped>
.text-right {
    text-align: right;
}

.d-inline-block {
    display: inline-block;
}

.header {
    padding-top: 10px;
}

.container-xl {
    --bs-gutter-x: 0, --my-home-div-height: 56px;
}

.min-height {
    --bs-gutter-x: 0
}

.rongliang {
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
    font-size: 14px;
    text-align: right;
    padding: 0;
}

.col-progress {
    align-items: center;
    padding-top: 15px;
    padding-right: 0;
}

.thead {
    font-weight: 700;
    height: 30px;
    line-height: 29px;
}


.thead2 {
    height: 30px;
    line-height: 29px;
}

.percentage-value {
    font-size: 10px;
    color: #fff;
    margin-left: -25px;
    height: 24px;
    line-height: 22px;
    display: inline-block;
}

.upload-demo {
    height: 48px;
    display: flex;
    justify-content: end;
}

.colbt {
    max-width: 484px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-left: 18px;
}
</style>
